<template>
  <el-upload
      class="avatar-uploader"
      :action="uploadApi"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      accept=".jpg,.jpeg,.png"
      title="必须先选择所属公司才能上传"
      :disabled="companyId === undefined"
      drag
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" :alt="alt"/>
    <el-icon v-else class="avatar-uploader-icon" @click="beforeUpload">
      <Plus/>
    </el-icon>
  </el-upload>
</template>

<script lang="ts" setup>
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'

import type {UploadProps} from 'element-plus'
import {computed, ref, watchEffect} from "vue";
import {getImageUrl} from "../utils/utils.ts";

const imageUrlInRemote = defineModel({
  type: String,
})
const imageUrl = ref()
const companyId = defineModel('companyId', {
  type: Number,
});
const departmentName = defineModel("departmentName", {
  type: String
});

let {alt, forStaff = false} = defineProps<{
  alt: string,
  forStaff?: boolean
}>();

watchEffect(()=> {
  if (imageUrlInRemote.value != undefined) {
    imageUrl.value = getImageUrl(imageUrlInRemote.value)
  } else {
    imageUrl.value = undefined;
  }
})

const uploadApi = computed(() => {
  let url = import.meta.env.VITE_API_BASE_URL + '/file?gs_id=' + companyId.value;
  if (forStaff) {
    url += '&bm_name=' + departmentName.value;
  }
  return url;
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    _response
) => {
  imageUrlInRemote.value = _response;
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('Avatar picture size can not exceed 5MB!')
    return false
  }
  return true
}

const beforeUpload = (event: any) => {
  if (companyId.value === undefined) {
    ElMessage.error("必须先选择所属公司才能上传")
    event.stopPropagation()
    return
  }

  if (forStaff && departmentName.value === undefined) {
    ElMessage.error('必须先选择所属部门才能上传');
    event.stopPropagation()
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>